import useOnMounted from "@/lib/hooks/useOnMounted";
import useOnUpdated from "@/lib/hooks/useOnUpdated";
import { debounce } from "@/lib/utils/debounce";
import echarts from "@/lib/utils/echarts";
import { useRef, type RefObject } from "react";

type ChartProps = {
  options?: echarts.EChartsCoreOption | null;
  className?: string;
  echarts?: RefObject<echarts.ECharts>;
};

export function useEchartsInstance() {
  const echartsRef = useRef<echarts.ECharts>(null);

  return echartsRef;
}

export default function Chart(props: ChartProps) {
  const { options, className, echarts: _echarts } = props;
  const elRef = useRef<HTMLDivElement>(null);
  const instanceRef = useRef<echarts.ECharts>();

  useOnMounted(() => {
    const instance = echarts.init(elRef.current!);
    if (_echarts) {
      // @ts-expect-error readonly ref
      _echarts.current = instance;
    }
    if (options) {
      instance.setOption(options);
    } else {
      instance.showLoading();
    }

    const onResize = debounce(function () {
      instance.resize();
    });
    window.addEventListener("resize", onResize);

    instanceRef.current = instance;

    const observer = new ResizeObserver(onResize);
    observer.observe(elRef.current!);

    return () => {
      instance.dispose();
      observer.disconnect();
      window.removeEventListener("resize", onResize);
    };
  });

  useOnUpdated(() => {
    if (options) {
      instanceRef.current!.hideLoading();
      instanceRef.current!.setOption(options);
    } else {
      instanceRef.current?.showLoading();
    }
  }, [options]);

  return <div className={className} ref={elRef}></div>;
}
